package com.ruoyi.framework.config;


import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * AES加密工具类
 */
public class AESEncryption {
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    public static String encrypt(String plainText, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(key.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Hex.encodeHexString(cipherText);
//        return Base64.getEncoder().encodeToString(cipherText);
    }

    //
    public static String decrypt(String cipherText, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(key.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
//        cipherText = cipherText.replace("\r", "").replace("\n", "");
//        byte[] encrypted = Base64.getDecoder().decode(cipherText);
        byte[] encrypted = Hex.decodeHex(cipherText);
        byte[] plainText = cipher.doFinal(encrypted);
        return new String(plainText, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        String plainText = "{\"groupName\":\"1\",\"userId\":1}";
        String key = "mN4Yn8Or8r7SH1w3";
        String cipherText = encrypt(plainText, key);
        System.out.println("Cipher text: " + cipherText);
        String decryptedText = decrypt(cipherText, key);
        System.out.println("Decrypted text: " + decryptedText);
        double a = 100 - 95.5 - 10;
        System.out.println(a);
    }
}